// 多例模式的类
class MultiInstance {
    private static final int MAX_INSTANCES = 3;
    private static MultiInstance[] instances = new MultiInstance[MAX_INSTANCES];
    private static int currentInstanceCount = 0;

    private MultiInstance() {
        // 私有化构造函数，防止外部实例化
    }

    // 获取实例的方法
    public static MultiInstance getInstance() {
        if (currentInstanceCount < MAX_INSTANCES) {
            if (instances[currentInstanceCount] == null) {
                instances[currentInstanceCount] = new MultiInstance();
            }
            currentInstanceCount++;
        } else {
            throw new IllegalStateException("Maximum number of instances reached");
        }
        return instances[currentInstanceCount - 1];
    }
}

// 客户端代码
public class MultiInstancePatternExample {
    public static void main(String[] args) {
        try {
            MultiInstance instance1 = MultiInstance.getInstance();
            MultiInstance instance2 = MultiInstance.getInstance();
            MultiInstance instance3 = MultiInstance.getInstance();
            // 试图获取第四个实例，应该抛出异常
            MultiInstance instance4 = MultiInstance.getInstance();
        } catch (IllegalStateException e) {
            System.out.println(e.getMessage()); // 输出 "Maximum number of instances reached"
        }
    }
}
